package org.javaboy.quartz_demo.job;

import jakarta.annotation.PostConstruct;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 不允许并发执行的 Job
 */
@DisallowConcurrentExecution
@Component
public class DisAllowConcurrentJob extends QuartzJobBean {
    @Autowired
    BeanFactory beanFactory;
    private SpelExpressionParser parser;
    private StandardEvaluationContext ctx;
    /**
     * 如果这里存在 jobExpression，那么系统会自动将 JobDataMap 中的属性映射到 jobExpression 变量中（会自动调用 setJobExpression）
     */
    private String jobExpression;

    public String getJobExpression() {
        return jobExpression;
    }

    public void setJobExpression(String jobExpression) {
        this.jobExpression = jobExpression;
    }
    /**
     * 初始化方法，在 Job 启动的时候执行，构造器执行完毕后执行
     */
    @PostConstruct
    public void init() {
        parser = new SpelExpressionParser();
        ctx = new StandardEvaluationContext();
        ctx.setBeanResolver(new BeanFactoryResolver(beanFactory));
    }

    /**
     * 这个是定时任务具体执行的方法，默认封装好的
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
//        String jobExp = context.getJobDetail().getJobDataMap().get(JobConstants.JOB_EXPRESSION).toString();
        parser.parseExpression(getJobExpression()).getValue(ctx);
    }
}
